import PropTypes from "prop-types";
import { useEffect } from "react";
import { useDispatch } from "react-redux";
import { Form, Input } from "antd-mobile";
import { REQUIRED_RULE } from "@common/constants";
import { createAction } from "@common/utils";
import { UPDATE_ORDER_MOVE_OPS_FORM_QTY } from "@store/order-move/action-types";

const ItemBlk = (props) => {
  const [form] = Form.useForm();
  const dispatch = useDispatch();

  useEffect(() => {
    if (props.item) {
      form.setFields([
        { name: "itemBarcode", value: props.item.itemBarcode },
        { name: "itemCode", value: props.item.itemCode },
        { name: "itemName", value: props.item.itemName },
        { name: "qty", value: props.item.qty },
        { name: "toLocation", value: props.item.toLocationName },
      ]);
    }
  }, [props.item]);

  const handleValChange = (changedValues) => {
    if (changedValues.qty || (typeof changedValues.qty === 'string' && changedValues.qty.length === 0)) {
      dispatch(
        createAction(UPDATE_ORDER_MOVE_OPS_FORM_QTY, {
          id: props.item.id,
          qty: changedValues.qty,
        })
      );
    }
  };

  const setItemBarcode = ({ barcode }) => {
    form.setFields([{ name: "itemBarcode", value: barcode }]);
  };

  const setToLocation = ({ parseResult }) => {
    form.setFields({ name: "toLocation", value: parseResult.locationName });
  };

  const checkQty = async (_, value) => {
    if (isNaN(value) || (typeof value === 'string' && value.length === 0)) {
      return Promise.reject("请输入数字");
    } else if (parseFloat(value) <= 0) {
      return Promise.reject(`数量须大于0`);
    }
    return Promise.resolve();
  };

  return (
    <Form form={form} mode="card" onValuesChange={handleValChange}>
      <Form.Item
        name="itemBarcode"
        label="物料条码"
        rules={REQUIRED_RULE}
        extra={<a onClick={() => props.markScanItem({ type: 'itemBarcode', callback: setItemBarcode})}>扫码</a>}
      >
        <Input placeholder="扫码获取" readOnly />
      </Form.Item>
      <Form.Item name="itemCode" label="物料编码">
        <Input readOnly />
      </Form.Item>
      <Form.Item name="itemName" label="物料名称">
        <Input readOnly />
      </Form.Item>
      <Form.Item
        name="qty"
        label="数量"
        rules={[
          {
            validator: (rule, value, callback) =>
              checkQty(rule, value, callback),
          },
        ]}
      >
        <Input placeholder="请扫码或输入" readOnly={props.item.isUnique} />
      </Form.Item>
      <Form.Item
        name="toLocation"
        label="移入库位"
        rules={REQUIRED_RULE}
        extra={<a onClick={() => props.markScanItem({ type: 'toLocation', callback: setToLocation })}>扫码</a>}
      >
        <Input placeholder="扫码获取" readOnly />
      </Form.Item>
    </Form>
  );
};

ItemBlk.propTypes = {
  item: PropTypes.object,
  markScanItem: PropTypes.func,
};

export default ItemBlk;
